package com.ruitu.mall_98_1.search;

import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.beanu.arad.Arad;
import com.beanu.arad.base.BaseFragment;
import com.beanu.arad.base.my_base.base_list.ListBaseAdapter;
import com.beanu.arad.base.my_base.base_list.SuperViewHolder;
import com.beanu.arad.utils.ToastUtils;
import com.beanu.arad.widget.MyPopWindow;
import com.ruitu.mall_98_1.R;
import com.ruitu.mall_98_1.product.activity.ProductListBySearchActivity;
import com.ruitu.router_module.AppHolder;
import com.ruitu.router_module.bean.EventModel;
import com.ruitu.router_module.bean.app.Area;
import com.ruitu.router_module.bean.product.Category;
import com.ruitu.router_module.bean.product.SearchCondition;
import com.ruitu.router_module.bean.product.SearchData;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

public abstract class SearchBaseFragment extends BaseFragment {
    protected View contentView;
    protected TextView tv_province, tv_city, tv_county;//省市区
    protected TextView tv_kinds1, tv_kinds2, tv_kinds3;//类型一 二 三
    protected TextView tv_ok;//搜索按钮
    protected EditText et_word;//用户输入的关键字
    protected RadioGroup rg_type;//下面两个的外层销售类型
    protected RadioButton rb_sale, rb_pre_sale;//厂家直销,厂家预售
    private LinearLayout ll_area;//选择区域的模块(地域版不需要选择区域,全国版需要选择区域)

    protected MyPopWindow popA1, popA2, popA3;//省 市 区 的弹窗
    protected MyPopWindow popK1, popK2, popK3;//类型一 二 三 的弹窗
    protected boolean ba1, ba2, ba3, bk1, bk2, bk3;//是否选择了
    protected int a1, a2, a3, k1, k2, k3;//记录选择的位置

    protected SearchData searchData;
    protected List<Area> areaList = new ArrayList<>();
    protected List<Category> categoryList = new ArrayList<>();

    //搜索功能需要的数据,点击搜索时解析出来
    protected String provinceId = "";
    protected String cityId = "";
    protected String countyId = "";
    protected String classA = "";
    protected String classB = "";
    protected String classC = "";
    protected String keys = "";
    protected String cityName = "";//当前项目所在的城市名称

    protected boolean isCityVersion = false;//当前是否是市域版
    protected String msgTxt = "当前为市域版,只能选择区县";//当前是否是市域版

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (Arad.bus.isRegistered(this)) {
            Arad.bus.unregister(this);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGetEvent(EventModel e) {
        if (e.getEventCode() == 181121) {//重置搜索条件
            if (isCityVersion) {//当前为市域版
                a3 = 0;
                ba1 = ba2 = true;
                ba3 = false;
                tv_province.setText(AppHolder.instance().getCITY().getParentName());
                tv_city.setText(AppHolder.instance().getCITY().getName());
                tv_county.setText("请选择");
            } else {
                a1 = a2 = a3 = 0;
                ba1 = ba2 = ba3 = false;
                tv_province.setText("请选择");
                tv_city.setText("请选择");
                tv_county.setText("请选择");
            }

            k1 = k2 = k3 = 0;
            bk1 = bk2 = bk3 = false;
            tv_kinds1.setText("请选择");
            tv_kinds2.setText("请选择");
            tv_kinds3.setText("请选择");

            if (isCityVersion) {
                countyId = classA = classB = classC = "";
            } else {
                provinceId = cityId = countyId = classA = classB = classC = "";
            }
            et_word.setText("");
        }
        if (e.getEventCode() == 19030151) {
            Bundle bundle = new Bundle();
            SearchCondition condition = new SearchCondition();
            condition.setKeys((String) e.getEventObj());
            bundle.putSerializable("condition", condition);
            startActivity(ProductListBySearchActivity.class, bundle);
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Arad.bus.register(this);
        try {
            searchData = (SearchData) getArguments().getSerializable("searchData");
            areaList = searchData.getCityies();
            categoryList = searchData.getClassificationList();
        } catch (Exception e) {
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        contentView = inflater.inflate(getContentViewId(), container, false);
        return contentView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        tv_province = contentView.findViewById(R.id.tv_province);
        tv_city = contentView.findViewById(R.id.tv_city);
        tv_county = contentView.findViewById(R.id.tv_county);
        tv_kinds1 = contentView.findViewById(R.id.tv_kinds1);
        tv_kinds2 = contentView.findViewById(R.id.tv_kinds2);
        tv_kinds3 = contentView.findViewById(R.id.tv_kinds3);
        tv_ok = contentView.findViewById(R.id.tv_ok);
        et_word = contentView.findViewById(R.id.et_word);
        rg_type = contentView.findViewById(R.id.rg_type);
        rb_sale = contentView.findViewById(R.id.rb_sale);
        rb_pre_sale = contentView.findViewById(R.id.rb_pre_sale);
        ll_area = contentView.findViewById(R.id.ll_area);

        tv_province.setOnClickListener(this);
        tv_city.setOnClickListener(this);
        tv_county.setOnClickListener(this);
        tv_kinds1.setOnClickListener(this);
        tv_kinds2.setOnClickListener(this);
        tv_kinds3.setOnClickListener(this);
        tv_ok.setOnClickListener(this);

        Area c = AppHolder.instance().getCITY();
        if (TextUtils.equals("全国版", c.getName()) || TextUtils.isEmpty(c.getName())
                || TextUtils.isEmpty(c.getId()) || TextUtils.isEmpty(c.getParentName())
                || TextUtils.isEmpty(c.getParentId())) {
//            ll_area.setVisibility(View.VISIBLE);
//            contentView.findViewById(R.id.divider0).setVisibility(View.VISIBLE);
            //全国版
            isCityVersion = false;
        } else {
//            ll_area.setVisibility(View.GONE);
//            contentView.findViewById(R.id.divider0).setVisibility(View.GONE);
            //市域版 只能选择区县
            isCityVersion = true;
            ba1 = ba2 = true;
            //市域版 默认是有省份和名字的
            tv_province.setText(AppHolder.instance().getCITY().getParentName());
            tv_city.setText(AppHolder.instance().getCITY().getName());

            a1 = getProIndex(c);
            a2 = getCityIndex(a1, c);
        }
    }

    //遍历省份列表,找出当前省份索引
    private int getProIndex(Area c) {
        for (int i = 0; i < areaList.size(); i++) {
            if (TextUtils.equals(areaList.get(i).getId(), c.getParentId())) {
                return i;
            }
        }
        return 0;
    }

    //遍历城市列表,找出当前城市索引
    private int getCityIndex(int proIndex, Area c) {
        Area pro = areaList.get(proIndex);//pro是一个省
        for (int i = 0; i < pro.getCityList().size(); i++) {
            if (TextUtils.equals(pro.getCityList().get(i).getId(), c.getId())) {
                return i;//当前市域版城市索引
            }
        }
        return 0;
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (v == tv_province) {
            if (isCityVersion) {
                ToastUtils.showShort(msgTxt);
                return;
            }
            if (isDataEmpty(areaList)) {
                ToastUtils.showShort("暂无开通的省份");
                return;
            }
            initPopupWindowCity(areaList, 11);
            popA1.showAsDropDown(tv_province);
        }
        if (v == tv_city) {
            if (isCityVersion) {
                ToastUtils.showShort(msgTxt);
                return;
            }
            if (!ba1) {
                ToastUtils.showShort("请先选择省份");
                return;
            }
            if (isDataEmpty(areaList.get(a1).getCityList())) {
                ToastUtils.showShort("暂无开通的城市");
                return;
            }
            initPopupWindowCity(areaList.get(a1).getCityList(), 12);
            popA2.showAsDropDown(tv_city);
        }
        if (v == tv_county) {
            if (!ba2) {
                ToastUtils.showShort("请先选择城市");
                return;
            }
            if (isDataEmpty(areaList.get(a1).getCityList().get(a2).getCityList())) {
                ToastUtils.showShort("暂无开通的区县");
                return;
            }
            initPopupWindowCity(areaList.get(a1).getCityList().get(a2).getCityList(), 13);
            popA3.showAsDropDown(tv_county);
        }
        if (v == tv_kinds1) {
            initPopupWindowKinds(popK1, categoryList, 21);
            popK1.showAsDropDown(tv_kinds1);
        }
        if (v == tv_kinds2) {
            if (!bk1) {
                ToastUtils.showShort("请先选择上一个类型");
                return;
            }
            if (isDataEmpty(categoryList.get(k1).getNodes())) {
                ToastUtils.showShort("该分类无数据");
                return;
            }
            initPopupWindowKinds(popK2, categoryList.get(k1).getNodes(), 22);
            popK2.showAsDropDown(tv_kinds2);
        }
        if (v == tv_kinds3) {
            if (!bk2) {
                ToastUtils.showShort("请先选择上一个类型");
                return;
            }
            if (isDataEmpty(categoryList.get(k1).getNodes().get(k2).getNodes())) {
                ToastUtils.showShort("该分类无数据");
                return;
            }
            initPopupWindowKinds(popK3, categoryList.get(k1).getNodes().get(k2).getNodes(), 23);
            popK3.showAsDropDown(tv_kinds3);
        }
        if (v == tv_ok) {//开始搜索
            if (null == searchData || isDataEmpty(searchData.getCityies())
                    || isDataEmpty(searchData.getClassificationList())) {
                ToastUtils.showShort("暂无搜索条件");
                return;
            }
            genData();//生成搜索需要的数据;
            executeSearch();
        }
    }

    protected SearchCondition condition;

    //生成搜索需要的数据;
    private void genData() {
        if (isCityVersion) {
            provinceId = AppHolder.instance().getCITY().getParentId();
            cityId = AppHolder.instance().getCITY().getId();
        } else {
            if (ba1) provinceId = areaList.get(a1).getId();
            if (ba2) cityId = areaList.get(a1).getCityList().get(a2).getId();
        }
        if (ba3) countyId = areaList.get(a1).getCityList().get(a2).getCityList().get(a3).getId();

        if (bk1) classA = categoryList.get(k1).getId();
        if (bk2) classB = categoryList.get(k1).getNodes().get(k2).getId();
        if (bk3) classC = categoryList.get(k1).getNodes().get(k2).getNodes().get(k3).getId();

        keys = et_word.getText().toString().trim();//用户输入的关键字
        cityName = AppHolder.instance().getCITY().getName();//当前项目城市版本
//        cityName = "";//当前项目城市版本

        condition = new SearchCondition();
        condition.setProvinceId(provinceId);
        condition.setCityId(cityId);
        condition.setCountyId(countyId);
        condition.setClassA(classA);
        condition.setClassB(classB);
        condition.setClassC(classC);
        condition.setKeys(keys);
        condition.setCityName(cityName);

        if (null != rb_pre_sale) {
            String goodSaleModel = rb_pre_sale.isChecked() ? "1" : "2";//1 预售 2 直销
            condition.setGoodSaleModel(goodSaleModel);
        }

        condition.setStatus(getSearchType());
    }

    private void setPopInfo(MyPopWindow mPop) {
        mPop.setFocusable(true);
//        mPop.setBackgroundDrawable(new ColorDrawable(66000000));
        mPop.setBackgroundDrawable(new ColorDrawable(00000000));
        mPop.setOutsideTouchable(true);
    }

    private View popViewArea;

    protected void initPopupWindowCity(final List<Area> areaList, final int flag) {
        popViewArea = View.inflate(getActivity(), R.layout.pop_search_list, null);
        if (flag == 11) {
            popA1 = new MyPopWindow(popViewArea, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            setPopInfo(popA1);
        } else if (flag == 12) {
            popA2 = new MyPopWindow(popViewArea, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            setPopInfo(popA2);
        } else if (flag == 13) {
            popA3 = new MyPopWindow(popViewArea, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            setPopInfo(popA3);
        }
        RecyclerView rcv_list = popViewArea.findViewById(R.id.rcv_list);
        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        rcv_list.setLayoutManager(manager);
        final AreaListAdapter adapter = new AreaListAdapter(getActivity());
        rcv_list.setAdapter(adapter);
        adapter.setDataList(areaList);
        adapter.setOnItemClickListener(new ListBaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View itemView, int position) {
                if (flag == 11) {
                    popA1.dismiss();
                    ba1 = true;
                    a1 = position;
                    tv_province.setText(areaList.get(position).getName());
                    //设置完成自身的数据,需要重置后面两项的数据
                    a2 = a3 = 0;
                    ba2 = ba3 = false;
                    tv_city.setText("请选择");
                    tv_county.setText("请选择");
                    cityId = "";
                    countyId = "";
                }
                if (flag == 12) {
                    popA2.dismiss();
                    ba2 = true;
                    a2 = position;
                    tv_city.setText(areaList.get(position).getName());
                    //设置完成自身的数据,需要重置后面一项的数据
                    a3 = 0;
                    ba3 = false;
                    tv_county.setText("请选择");
                    countyId = "";
                }
                if (flag == 13) {
                    popA3.dismiss();
                    ba3 = true;
                    a3 = position;
                    tv_county.setText(areaList.get(position).getName());
                }
            }
        });
    }

    private View popViewKinds;

    protected void initPopupWindowKinds(MyPopWindow mPop, final List<Category> categoryList, final int flag) {
        popViewKinds = View.inflate(getActivity(), R.layout.pop_search_list, null);
        if (flag == 21) {
            popK1 = new MyPopWindow(popViewKinds, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            setPopInfo(popK1);
        } else if (flag == 22) {
            popK2 = new MyPopWindow(popViewKinds, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            setPopInfo(popK2);
        } else if (flag == 23) {
            popK3 = new MyPopWindow(popViewKinds, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            setPopInfo(popK3);
        }
        RecyclerView rcv_list = popViewKinds.findViewById(R.id.rcv_list);
        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        rcv_list.setLayoutManager(manager);
        CategoryListAdapter adapter = new CategoryListAdapter(getActivity());
        rcv_list.setAdapter(adapter);
        adapter.setDataList(categoryList);
        adapter.setOnItemClickListener(new ListBaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View itemView, int position) {
                if (flag == 21) {
                    popK1.dismiss();
                    bk1 = true;
                    k1 = position;
                    tv_kinds1.setText(categoryList.get(position).getTypeName());
                    //设置完成自身的数据,需要重置后面两项的数据
                    k2 = k3 = 0;
                    bk2 = bk3 = false;
                    tv_kinds2.setText("请选择");
                    tv_kinds3.setText("请选择");
                    classB = "";
                    classC = "";
                }
                if (flag == 22) {
                    popK2.dismiss();
                    bk2 = true;
                    k2 = position;
                    tv_kinds2.setText(categoryList.get(position).getTypeName());
                    //设置完成自身的数据,需要重置后面一项的数据
                    k3 = 0;
                    bk3 = false;
                    tv_kinds3.setText("请选择");
                    classC = "";
                }
                if (flag == 23) {
                    popK3.dismiss();
                    bk3 = true;
                    k3 = position;
                    tv_kinds3.setText(categoryList.get(position).getTypeName());
                }
            }
        });
    }

    protected class AreaListAdapter extends ListBaseAdapter<Area> {

        public AreaListAdapter(Context context) {
            super(context);
        }

        @Override
        public int getLayoutId() {
            return R.layout.pop_item_search_list;
        }

        @Override
        public void onBindItemHolder(SuperViewHolder holder, int position) {
            TextView tv_name = holder.getView(R.id.tv_name);
            tv_name.setText(mDataList.get(position).getName());
        }
    }

    protected class CategoryListAdapter extends ListBaseAdapter<Category> {

        public CategoryListAdapter(Context context) {
            super(context);
        }

        @Override
        public int getLayoutId() {
            return R.layout.pop_item_search_list;
        }

        @Override
        public void onBindItemHolder(SuperViewHolder holder, int position) {
            TextView tv_name = holder.getView(R.id.tv_name);
            tv_name.setText(mDataList.get(position).getTypeName());
        }
    }

    protected abstract int getContentViewId();//获取布局资源id

    protected abstract String getSearchType();//获取搜索类型 0 商品 1 企业

    protected abstract void executeSearch();//执行搜索逻辑
}
